package heven.holt.wan.android.paging.source

import androidx.paging.PagingSource
import androidx.paging.PagingState
import heven.holt.wan.android.api.ApiWanArticleServer
import heven.holt.wan.android.model.ArticleModel

class WanArticlePagingSource(
    private val apiWanArticleServer: ApiWanArticleServer
) : PagingSource<Int, ArticleModel>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleModel> {
        return try {
            val page = params.key ?: 0
            val response = apiWanArticleServer.listArticle(page)
            val datas = response.data?.datas?.toMutableList() ?: mutableListOf()
            if (page == 0) {//如果是第一页，添加置顶数据
                val topResponse = apiWanArticleServer.topArticle()
                val topData = topResponse.data ?: listOf()
                topData.forEach { it.top = true }
                datas.addAll(0, topData)
            }
            val curPage = response.data?.curPage ?: 1
            LoadResult.Page(
                data = datas,
                prevKey = if (curPage <= 1) null else page - 1,
                nextKey = if (curPage >= response.data?.pageCount ?: 0) null else page + 1
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, ArticleModel>): Int? = null
}